﻿using System.Linq;

namespace TraceView.UI.Entities
{
    //Base class for a filtered TraceItem collection, such as the recent items collection
    public abstract class FilteredTraceItemCollection : BaseEntityCollection<TraceItem>
    {
        private readonly TraceItemCollection _masterList;
        private readonly IFilterCollectionMatchCriteria[] _filters;

        public void RebuildList()
        {
            Clear();
            foreach (TraceItem item in _masterList)
                Add(item);
        }

        protected FilteredTraceItemCollection(TraceItemCollection masterList, IFilterCollectionMatchCriteria[] filters)
        {
            _masterList = masterList;
            _filters = filters;
            foreach (IFilterCollectionMatchCriteria filter in _filters)
                filter.FilterChanged += OnFilterChanged;
        }

        private void OnFilterChanged()
        {
            RebuildList();
        }

        protected override sealed void InsertItem(int index, TraceItem item)
        {
            if (_filters == null)
                base.InsertItem(0, item);
            else if (_filters.All(filter => filter.MatchCriteria(item)))
                base.InsertItem(0, item);
        }
    }
}